package model;

import java.util.*;


public class ShoppingCart {
    HashMap<Integer, GoodsItem> items;

    public ShoppingCart() {
        this.items = new HashMap<>();
    }
    public void add(GoodsItem goodsItem) {
        int productId = goodsItem.getProduct().getPid();

        // 如果购物车中包含指定的商品，返回该商品并增加数量
        if (items.containsKey(productId)) {
            GoodsItem scItem = items.get(productId);
            // 修改该商品的数量
            scItem.setQuantity(scItem.getQuantity() + goodsItem.getQuantity());

        } else {
            items.put(productId, goodsItem);
        }
    }

    public void remove(Integer productId) {
        if (items.containsKey(productId)) {
            GoodsItem scItem = items.get(productId);
            scItem.setQuantity(scItem.getQuantity()-1);
            if (scItem.getQuantity() <= 0) {
                items.remove(productId);
            }
        }
    }

    public Collection<GoodsItem> getItems() {
        return items.values();
    }

    public double getTotal() {
        double amount = 0.0;
        for (GoodsItem item : getItems()) {
            Product product = item.getProduct();
            amount += item.getQuantity() * product.getPrice();
        }
        return roundOff(amount);
    }

    private double roundOff(double x) {
        long val = Math.round(x * 100);
        return val / 100.0;
    }

    public void clear() {
        items.clear();
    }
}
